package ipgather.core.host.thread;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.Proxy.Type;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.io.FileUtils;

import ipgather.constant.PortConstant;
import ipgather.entity.Host;

public class HostMain {

	//半打扫描（half-open scanning），即TCP SYN scan。它利用了TCP连接建立三次握手的第一步，并且没有建立一个完整的TCP连接。实现办法是向远端主机某端口发送一个只有SYN标志位的TCP报文段，如果主机反馈一个SYN|ACK数据包，那么，这个主机正在监听该端口，如果反馈的是RST数据包，说明，主机没有监听该端口。在X-Scanner扫描工具上就有SYN的选择项
	//http://moogates.bokee.com/594885.html
	
	public Integer threads = 0;
	
	public static void main(String[] args) {	
		File file = new File(HostMain.class.getResource("/").getPath()+File.separator+"ranges"+File.separator+"China.txt");
		System.out.println(file.getAbsolutePath());
		try {
			List<String> lines = FileUtils.readLines(file, Charset.forName("utf-8"));
			//59.191.240.0	60.31.255.255
			final char POINT = '.';
			String createIP = null;
			HostMain hostMain = new HostMain();
			for(String line : lines){
				String start = line.split("\t")[1];
				String end = line.split("\t")[2];
				String[] startArr = start.split("[.]");
				String[] endArr = end.split("[.]");
				int[] sta = {Integer.parseInt(startArr[0]),Integer.parseInt(startArr[1]),Integer.parseInt(startArr[2]),Integer.parseInt(startArr[3])};
				int[] ena = {Integer.parseInt(endArr[0]),Integer.parseInt(endArr[1]),Integer.parseInt(endArr[2]),Integer.parseInt(endArr[3])};
				for(int i1 = sta[0];i1<=ena[0];i1++){
					for(int i2 = sta[1];i2<=ena[1];i2++){
						for(int i3 = sta[2];i3<=ena[2];i3++){
							for(int i4 = sta[3];i4<=ena[3];i4++){
								createIP = new StringBuilder(7).append(i1).append(POINT).append(i2).append(POINT).append(i3).append(POINT).append(i4).toString();
								hostMain.check(createIP);
							}
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void check(String createIP){
		HostMain hm = this;
		boolean hasMax = true;
		try {
			while(hasMax){
				if(this.threads>=4000){
					Thread.sleep(100);
				}else{
					hasMax = false;
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		synchronized (this.threads) {
			this.threads++;
		}
		final String ip = createIP;
		new Thread(new Runnable() {
			@Override
			public void run() {
				hm.checkCollect(ip,8080);
				synchronized (hm.threads) {
					hm.threads--;
				}
			}
		}).start();
		//hostMain.checkProxyHost(createIP,80);
	}
	static URL URL = null;
	static{
		try {
			URL = new URL("http://www.haosou.com/");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	public boolean checkProxyHost(String host,int port){
		InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
		boolean p = false;
		try {
			URLConnection connection = URL.openConnection(new Proxy(Type.HTTP, proxyAddr));
			connection.setConnectTimeout(3000);
			String content = convertStreamToString(connection.getInputStream());
			if(0!=connection.getDate()&&content.contains("好搜 — 用好搜，特顺手")){
				System.err.println("通过");
				p = true;
			}
		} catch (IOException e) {
		}
		return p;
	}
	
	public boolean checkCollect(String host,int port){
		Socket socket = new Socket();
		boolean pass = true;
		try {
			socket.connect(new InetSocketAddress(host,port),2000);
			System.out.println("yes");
		} catch (UnknownHostException e) {
			pass = false;
		}catch (SocketTimeoutException to) {
			pass = false;
		} catch (IOException e) {
			pass = false;
		} finally {
			if(null!=socket&&!socket.isClosed()){
				try {
					socket.close();
				} catch (IOException e) {
					pass = false;
				}
			}
		}
		return pass;
	}
	
	private String convertStreamToString(InputStream is) {
		if (null == is){
			return "";
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line.trim());
			}
		} catch (IOException e) {
			//e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}
		return sb.toString();

	}
}
